package tcpEcho;

import udpEcho.Server;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.Scanner;

public class Client {
    //先连接默认值
    public Socket socket = null;
    //传入要访问的服务器的ip和端口号
    public Client(String serverIp,int serverPort) throws IOException {
        //初始化连接，让连接保存服务器ip和端口号
        socket = new Socket(serverIp,serverPort);
    }
    public void start(){
        //日志
        System.out.println("客户端上线");
        try(InputStream inputStream = socket.getInputStream();
                OutputStream outputStream = socket.getOutputStream()) {
            //读取要发送
            Scanner scanner = new Scanner(System.in);
            //读取接收的字符串数组，并用Scanner包装
            Scanner scannerNextWork = new Scanner(inputStream);
            //写（发送）
            PrintWriter writer = new PrintWriter(outputStream);
            while(true){
                //提示用户输入
                System.out.printf("-> ");
                //读取发送的并包装成String
                String request = scanner.next();
                //发送到服务器
                writer.println(request);
                //冲刷本次传入writer缓冲区
                writer.flush();
                //出口
                if(!scannerNextWork.hasNext()){
                    break;
                }
                //对收到的字符流包装成String
                String response = scannerNextWork.next();
                //打印
                System.out.println(response);
            }
        }catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    public static void main(String[] args) throws IOException {
        //传入服务器的ip的端口号
        Client client = new Client("127.0.0.1",2020);
        //启动
        client.start();

    }
}
